<?php

class SiteController extends Controller {

	/**
	 * Declares class-based actions.
	 */
	public function actions() {
		return array(
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex() {
		$join = 'translations';
		$config = array(
			'criteria'=>array(
				'select'=>array('t.*', "$join.dialect"),
				'distinct'=>true,
				'join'=>"INNER JOIN $join ON $join.languageId = t.id",
				'order'=>'translations.updatedAt DESC',
				'limit'=>6,
			),
			'pagination'=>false,
		);
		$table = 'Language';
		$translationDataProvider = new CActiveDataProvider($table, $config);

		$config = array(
			'criteria'=>array(
				'order'=>'updatedAt DESC',
				'limit'=>50,
			),
			'pagination'=>array(
				'pageSize'=>5,
			),
		);
		$languageDataProvider = new CActiveDataProvider('Language', $config);

		$data = array(
			'languageDataProvider'=>$languageDataProvider,
			'translations'=>$translationDataProvider->data,
		);
		$this->render('index', $data);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError() {
		if ($error = Yii::app()->errorHandler->error) {
			if (Yii::app()->request->isAjaxRequest) echo $error['message'];
			else $this->render('error', $error);
		}
	}

	public function actionMigrate() {
		$commandPath = Yii::app()->getBasePath() . '/' . 'commands';
		$runner = new CConsoleCommandRunner();
		$runner->addCommands($commandPath);
		$commandPath = Yii::getFrameworkPath() . '/cli/' . 'commands';
		$runner->addCommands($commandPath);
		$args = array('yiic', 'migrate', '--interactive=0');
		ob_start();
		$runner->run($args);
		echo '<pre style="font-family: Consolas, Menlo; font-size: 1em;">' .
		htmlentities(ob_get_clean(), null, Yii::app()->charset) .
		'</pre>';
	}

	protected function performPostAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'post-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}